﻿using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace GUI.Services.VietID
{
    /// <summary>
    /// Summary description for VietIdHandler
    /// </summary>
    public class VietIdHandler : IHttpHandler
    {


        public void ProcessRequest(HttpContext context)
        {
            string command;
            if (context.Request.RequestType == "POST")
            {
                if (context.Request["command"] != null)
                {
                    command = context.Request["command"];
                }
                else
                {
                    return;
                }
            }
            else
            {
                if (context.Request.QueryString["command"] != null)
                {
                    command = context.Request.QueryString["command"];
                }
                else
                {
                    return;
                }
            }

            switch (command.ToLower())
            {
                case "checksession":
                    CheckSession(context);
                    break;
            }
        }

        private void CheckSession(HttpContext context)
        {
            string output;
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                var ident = HttpContext.Current.User.Identity as FormsIdentity;

                if (ident != null)
                {
                    FormsAuthenticationTicket ticket1 = ident.Ticket;
                    string[] userData = ticket1.UserData.Split('|');
                    try
                    {
                        string id = userData[0];
                        string username = userData[1];
                        string email = userData[2];
                        string fullName = userData[3];
                        string gender = userData[5];

                        output = "{'id':'" + id
                            + "', 'username':'" + username
                            + "', 'email':'" + email
                            + "', 'full_name':'" + fullName
                            + "', 'gender':'" + gender + "'}";
                    }
                    catch
                    {
                        output = "";
                    }
                }
                else
                {
                    output = "";
                }

            }
            else
            {
                output = "";
            }
            var objSerial = new JavaScriptSerializer();
            var json = objSerial.Serialize(output);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}